package cz.mendelu.swi2.skladDilu.controllers;

import javax.validation.Valid;
import org.springframework.validation.BindingResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cz.mendelu.swi2.skladDilu.Part;
import cz.mendelu.swi2.skladDilu.Warehouse;
import cz.mendelu.swi2.skladDilu.Forms.FEditForm;


@Controller
@RequestMapping("/skladdilu/addpart")
public class CAddPartController {

	@Autowired   
	private Warehouse warehouse;


	@RequestMapping(method = RequestMethod.GET)
	public String showForm() {
		
		 return "addPart";
	}

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView processForm(@Valid FEditForm addForm, BindingResult result) {
		ModelAndView mview;
		if (result.hasErrors()) {
			
			mview= new ModelAndView("addPart") ;
			mview.addObject("message","Chyba ve vstupnich datech");
			mview.addObject("error",true);
		
		}
		else
		{
		Part pridani = new Part(addForm.getUid(),addForm.getName(),addForm.getCount(),addForm.getDetails());
		if(warehouse.addPart(pridani))
		{
			 mview = new ModelAndView("skladDilu") ;
	        mview.addObject("listDilu", warehouse.getListOfParts()) ;
	        mview.addObject("inventura",false);
		   
		}
		else
		{
			mview= new ModelAndView("addPart") ;
			mview.addObject("message","Chyba vlozeni");
			mview.addObject("error",true);
			
		}
		}
		return mview;
	}
  }
